<template>
  <a-select
    v-model:value="value"
    placeholder="Select a person"
    show-search
    :options="options"
    :filter-option="false"
    @search="fetchUser"
    @focus="handleFocus"
    @blur="handleBlur"
    @change="handleChange"
    style="width: 100%"
    :dropdown-match-select-width="false"
    option-label-prop="name"
  ></a-select>
</template>
<script lang="ts" setup name="JinHuiDealerSelect">
  import type { SelectProps } from 'ant-design-vue';
  import { queryDealerCodeAndNameList } from '/@/jinhui/components/DealerSelect/src/DealerApiAndData';
  import { simpleDebounce } from '/@/utils/jinhui/compUtils';
  import {ref, watch, defineProps} from 'vue';
  const props = defineProps({
    value: [Array, Object, String, Number],
    }
  )
  const options = ref<SelectProps['options']>([]);
  const optionsTwo = ref();

  queryDealerCodeAndNameList({ page: 1,rows: 100 }).then((info) => {
    if (info.rows) {
      options.value = info.rows.map((x) => {
        return {
          value: x.dealerName,
          label: x.dealerCode + '-' + x.dealerName,
          name: x.dealerName,
        };
      });
      optionsTwo.value=options.value;
    }
  });
  const emits = defineEmits(['change', 'update:value']);
  const handleChange = (value: string) => {
    emits('update:value', value);
    emits('change', value);
  };
  const handleBlur = () => {
    //options.value=optionsTwo.value
  };
  //监听value（dealerName的值），重置之后重新赋值前100条数据
  watch(
    () => props.value,
    (val) => {
      if(!val){
        options.value = optionsTwo.value;
        value.value = undefined;
      }
    }
  )


  const handleFocus = () => {
  };
  const filterOption = (input: string, option: any) => {
    return option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  let lastFetchId = 0;
  const fetchUser = simpleDebounce((value) => {
    lastFetchId += 1;
    const fetchId = lastFetchId;

    queryDealerCodeAndNameList({ page: 1,rows: 50, q: value }).then((body) => {
      if (fetchId !== lastFetchId) {
        // for fetch callback order
        return;
      }
      if (body.rows) {
        options.value = body.rows.map((x) => ({
          value: x.dealerName,
          label: x.dealerCode + '-' + x.dealerName,
          name: x.dealerName,
        }));
      }
    });
  }, 300);

  const value = ref<string | undefined>(undefined);


</script>
